package com.hfzy.ihk.web.linkcall;

import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo;
import com.hfzy.ihk.common.core.elasticsearch.OperationErrorMsgBiz;
import com.hfzy.ihk.common.web.context.AbstractGracefulShutDownServletInitializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by Administrator on 2017/12/1.
 *
 * @author wws
 */
//@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, RedisAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class})
/**
 * 与spring data elasticsearch一齐使用，必须禁止RedisAutoConfiguration
 * */
@SpringBootApplication(exclude = {
//        ElasticsearchAutoConfiguration.class,
        RedisAutoConfiguration.class,
        KafkaAutoConfiguration.class
})
@ComponentScan(basePackages = "com.hfzy.ihk")
@EnableElasticsearchRepositories({
        "com.hfzy.ihk.common.core.elasticsearch.repository.common",
        "com.hfzy.ihk.web.linkcall.dao"
})
@EnableDubbo(scanBasePackages = "com.hfzy.ihk.web.linkcall.serviceImpl")
@EnableScheduling
@EnableRedisHttpSession
//@ServletComponentScan
@EnableAsync
//@EnableTransactionManagement
//@EnableCaching
@EnableAspectJAutoProxy(exposeProxy = true)
public class Application extends AbstractGracefulShutDownServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(1000);
        executor.setThreadNamePrefix("linkCallTaskExecutor-");

        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(30);
        return executor;
    }

    @Autowired
    OperationErrorMsgBiz operationErrorMsgBiz;

    /**
     * 可以用个这个RestTemplate 来进行个服务器之间的调用，由于 开启了EnableOAuth2Sso  这里调用的时候会自动添加token
     * @param resource
     * @param context
     * @return
     */
    @Bean("restOperations")
    public OAuth2RestOperations restOperations(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) {
        OAuth2RestOperations ou =  new OAuth2RestTemplate(resource, context);
        return ou;
    }

//    @Bean
//    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
//        return (String... args) -> {
//            String[] beanNames = ctx.getBeanDefinitionNames();
//            Arrays.sort(beanNames);
//            for (String beanName : beanNames) {
//                System.out.println(beanName);
//            }

//            operationErrorMsgBiz.dealElasticsearchOperation(
//                    new ElasticsearchOperation("111",
//                            LinkCallTables.TEST_LOG.getTableName(),
//                            LinkCallOperations.addTestLog.getOperationName(),
//                            new TestLog(UUIDs.base64UUID(),"testwws")
//                    ),new RuntimeException("测试的啊"));

//            OperationErrorMsg optErrorMsg = null;
//                optErrorMsg = new OperationErrorMsg();
//                optErrorMsg.setId(org.elasticsearch.common.UUIDs.base64UUID());
//                optErrorMsg.setCreateTime(new Date());
//                optErrorMsg.setTxId( UUIDs.base64UUID());
//                optErrorMsg.setTopic(null);
//                optErrorMsg.setPartition(null);
//                optErrorMsg.setOptTable(TestLog.class.getName());
//                optErrorMsg.setOptMethod(LinkCallOperations.addTestLog.getOperationName());
//                String json = JSON.toJSONString(Lists.newArrayList( new TestLog(org.elasticsearch.common.UUIDs.base64UUID(),"wwsTestLog")));
//                optErrorMsg.setJsonArrayMessage(json);
//                optErrorMsg.setExceptionMsg(null);
//
//            ElasticsearchLocalCache.put(optErrorMsg);
//
//
//            VersionCtrlErrorMsg versionCtrlErrorMsg2 = new VersionCtrlErrorMsg();
//            versionCtrlErrorMsg2.setId(org.elasticsearch.common.UUIDs.base64UUID());
//            versionCtrlErrorMsg2.setRedisKey(LinkCallRedisVersionKey.TABLE_TEST_Entity.getVersionKeyName());
//            versionCtrlErrorMsg2.setDataId("AWU8fPC243Ut1bsyKES_");
//            versionCtrlErrorMsg2.setOptTable( LinkCallTables.TEST_ENTITY.getTableName());
//            versionCtrlErrorMsg2.setVersionOpt(VersionOperation.updateRedisVersion.getOperationName());
//            ElasticsearchLocalCache.put(versionCtrlErrorMsg2);
//
//            VersionCtrlErrorMsg versionCtrlErrorMsg = new VersionCtrlErrorMsg();
//            versionCtrlErrorMsg.setId(org.elasticsearch.common.UUIDs.base64UUID());
//            versionCtrlErrorMsg.setRedisKey(LinkCallRedisVersionKey.TABLE_TEST_Entity.getVersionKeyName());
//            versionCtrlErrorMsg.setDataId("AWU8fPC243Ut1bsyKES_");
//            versionCtrlErrorMsg.setOptTable( LinkCallTables.TEST_ENTITY.getTableName());
//            versionCtrlErrorMsg.setVersionOpt(VersionOperation.rollbackVersion.getOperationName());
//            versionCtrlErrorMsg.setRollbackValue(1);
//
//            ElasticsearchLocalCache.put(versionCtrlErrorMsg);
//
//            VersionCtrlErrorMsg versionCtrlErrorMsg3 = new VersionCtrlErrorMsg();
//            versionCtrlErrorMsg3.setId(org.elasticsearch.common.UUIDs.base64UUID());
//            versionCtrlErrorMsg3.setRedisKey(LinkCallRedisVersionKey.TABLE_TEST_Entity.getVersionKeyName());
//            versionCtrlErrorMsg3.setDataId("AWU8fPC243Ut1bsyKES_");
//            versionCtrlErrorMsg3.setOptTable( LinkCallTables.TEST_ENTITY.getTableName());
//            versionCtrlErrorMsg3.setVersionOpt(VersionOperation.deleteVersion.getOperationName());
//            versionCtrlErrorMsg3.setRollbackValue(1);
//
//            ElasticsearchLocalCache.put(versionCtrlErrorMsg3);

//        };
//    }


    /*@Bean
    public Connector httpConnector(){
        Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8880);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
    }*/
}
